﻿Imports Mystery
Imports System.Data


Public Class ContentSelectionWindow
    Implements IContentSelectionControl

    Private _controler As IContentSelectionControler

    Private _selection As IContent

    Public Property Controler As IContentSelectionControler Implements IContentSelectionControl.controler
        Get
            Return _controler
        End Get
        Set(value As IContentSelectionControler)
            _controler = value
            render()
        End Set
    End Property

    Public Event contentSelected(content As Mystery.IContent) Implements IContentSelectionControl.contentSelected

    Private ReadOnly Property search As String
        Get
            Return tbSearch.Text
        End Get
    End Property

    Public Sub searchChanged() Handles tbSearch.TextChanged
        render()
    End Sub

    Private Sub ContentSelectedHandler(guid As Guid)
        Dim cd As IContentDispatcher = getGlobalObject(Of IContentDispatcher)()
        _selection = cd.getContent(Of IContent)(guid)
        RaiseEvent contentSelected(_selection)
        Me.Close()
    End Sub

    Private Sub addContentInList(c As LightContentReferece)
        If c Is Nothing Then Exit Sub

        Dim li As New ListBoxItem
        li.Content = c.ref_text
        AddHandler li.MouseDoubleClick, Sub() ContentSelectedHandler(Guid.Parse(c.guid))
        tbContents.Items.Add(li)

    End Sub

    Private Sub render()
        If _controler Is Nothing Then Exit Sub
        tbContents.Items.Clear()
        Dim contents As New List(Of LightContentReferece)(_controler.getContents(search))
        contents.Sort(LightContentReferece.getComparer)
        For Each c As LightContentReferece In contents
            addContentInList(c)
        Next
    End Sub

End Class
